# Libraries ---------------------------------------------------------------

library(tidyverse)
library(haven)
library(zeligverse)

governadores <- read_dta("../data/data_final.dta") %>%
  mutate(uf_cod = as.numeric(as.character(uf_cod))) %>% 
  arrange(year) %>% 
  group_by(uf) %>% 
  mutate(l4vote = lag(elecvote, n=4L)) %>%
  mutate(un_ind2 = ind_serv * unempch_rel) %>% 
  filter(included == 1 & elecyear == 1) %>% 
  tbl_df()


# Estimating --------------------------------------------------------------

model <- Zelig::zelig(vote_share ~ l4vote + incumbent + tax + (unempch_rel  * ind_serv),
            model="ls",
            data=governadores,
            cite = F)


# Simulating --------------------------------------------------------------

# Set values at -2, -1, 0, 1 and 2 sd from the mean
xvalues <- mean(governadores$unempch_rel) + ((-2:2)*sd(governadores$unempch_rel))

# Simulate
model %>% 
  setx(unempch_rel =  xvalues) %>% # set x values for unempch_rel
  sim() %>% # simulate
  zelig_qi_to_df() %>% # convert to df
  qi_slimmer(qi_type = "ev", ci = 95) # generate ev


# Figure 5  ----------------------------------------------------------------

governadores %>% 
  filter(included == 1 & elecyear == 1) %>% 
  ggplot(aes(x = unempch_rel)) + 
  geom_rug() +
  geom_point(data = estimates,
             aes(x = unempch_rel, y = qi_ci_median)) +
  geom_segment(data = estimates,
               aes(x = unempch_rel, xend = unempch_rel,
                   y = qi_ci_min, yend = qi_ci_max), col = "black") +
  labs(y = "Predicted Value of Incumbent Party Vote Share",
       x = "Benchmark Change in Unemployment") +
  theme_minimal()

ggsave(plot = last_plot(), file="../figures/figure4.png", width = 10, height = 7.5)
